<template>
  <div>
    <!-- 搜索 和 操作  begin -->
    <div style="margin-bottom: 10px">
      <el-row :gutter="4">
        <el-col :md="6">
          <el-input v-model="query.username" clearable size="small" placeholder="可用户名搜索" class="filter-item" @keyup.enter.native="toQuery" />
        </el-col>
        <el-col :md="6">
          <el-input v-model="query.mobile" clearable size="small" placeholder="可手机号搜索" class="filter-item" @keyup.enter.native="toQuery" />
        </el-col>
        <el-col :md="6">
          <el-input v-model="query.nickname" clearable size="small" placeholder="可姓名/昵称搜索" class="filter-item" @keyup.enter.native="toQuery" />
        </el-col>
        <el-col :md="3">
          <div style="margin-top: 2px">
            <el-button type="success" size="mini" @click="toQuery">搜索</el-button>
          </div>
        </el-col>
        <el-col :md="3">
          <div style="margin-top: 2px">
            <el-popover
              v-model="visible"
              placement="left-end"
              width="200"
            >
              <p>确定要给选中的<span style="color: #1482f0">{{ selections.length }} 个用户</span>{{ isBinded?'【取消】':'【授予】' }}<span style="color: #ff1d34">{{ bindRoleName }}</span> 角色的权限吗?</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                <el-button size="mini" type="primary" :disabled="selections.length <= 0" :loading="bloading" @click="doOption">
                  确定
                </el-button>
              </div>
              <el-button
                v-if="(permission && permission.has('SysRoleUser:edit')&& isBinded) || (permission && permission.has('SysRoleUser:add')&& !isBinded)"
                slot="reference"
                :type="isBinded?'danger':'primary'"
                size="mini"
                :disabled="selections.length <= 0"
              >
                {{ isBinded?'取消授权':'授权' }}
              </el-button>
            </el-popover>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 搜索 和 操作  end -->
    <!-- 表格-->
    <el-table
      ref="table"
      v-loading="loading"
      :data="userData"
      border
      style="width: 100% "
      row-key="id"
      stripe
      tooltip-effect="dark"
      size="small"
      :highlight-current-row="true"
      @selection-change="selectionChangeHandler"
    >
      <el-table-column type="selection" width="39" />
      <el-table-column prop="username" label="用户名" sortable="custom" />
      <el-table-column prop="mobile" label="手机号" sortable="custom" />
      <el-table-column prop="email" label="邮箱" sortable="custom" />
      <el-table-column prop="nickname" label="姓名" sortable="custom" />
      <el-table-column label="操作" width="120" header-align="center" align="center">
        <!--表格 内部操作-->
        <template slot-scope="scope">
          <el-popover
            v-model="scope.row.binding"
            placement="left-end"
            trigger="click"
            width="200"
          >
            <p>确定要给<span style="color: #1482f0">{{ scope.row.username }} </span>{{ isBinded?'【取消】':'【授予】' }}<span style="color: #ff1d34">{{ bindRoleName }}</span> 角色的权限吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.binding = false">取消</el-button>
              <el-button type="primary" size="mini" :loading="bloading" @click="bindUserId(scope.row)">确定</el-button>
            </div>
            <el-button
              v-if="(permission && permission.has('SysRoleUser:edit')&& isBinded) || (permission && permission.has('SysRoleUser:add')&& !isBinded)"
              slot="reference"
              :type="isBinded?'danger':'primary'"
              plain
              size="mini"
            >{{ isBinded?'取消授权':'授权' }}</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size.sync="page.size"
      :total="Number(page.total)"
      :current-page.sync="page.current"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChangeHandler($event)"
      @current-change="pageChangeHandler"
    />
  </div>
</template>

<script>
import { getUsersByRoleIdNotBind, getUsersByRoleId, removeUserIdsByRoleId, addUserIdsByRoleId } from '@/api/sys/UserRole'
export default {
  name: 'UserList',
  props: {
    isBinded: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      bloading: false,
      userData: [],
      permission: new Map(),
      accredit: false,
      bindRoleId: '',
      bindRoleName: '',
      page: {
        size: 10,
        total: 0,
        current: 1
      },
      userIds: [],
      selections: [],
      query: {
        roleId: '',
        username: null,
        mobile: null,
        nickname: null
      }
    }
  },
  mounted() {
    // this.$emit('initdata', { tag: { name: 'isBinded' }})
    // 暂时这么处理，为了避免组件第一次加载的时候没有数据
    this.permission = this.$store.state.menu.buttonPermission.get('SysRole')
    try {
      this.getUsersData(this.$parent.$parent.$parent.$parent.bindRoleId, this.$parent.$parent.$parent.$parent.bindRoleName, true)
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    // 查询
    toQuery() {
      this.getUsersData(this.bindRoleId, this.bindRoleName, this.isBinded)
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.page.current = e
      this.toQuery()
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.page.size = e
      this.page.current = 1
      this.toQuery()
    },
    // 获取用户数据
    getUsersData(bindRoleId, bindRoleName, isbind) {
      this.selections = []
      this.loading = true
      if (bindRoleId) {
        this.bindRoleId = bindRoleId
      }
      if (bindRoleName) {
        this.bindRoleName = bindRoleName
      }
      this.query.roleId = this.bindRoleId
      const param = {
        ...this.query,
        ...this.page
      }
      if (isbind) { // 获取已绑定的用户
        getUsersByRoleId(param).then(res => {
          if (res.data && res.data.results) {
            this.userData = res.data.results
            this.page.total = res.data.total
          }
          setTimeout(() => {
            this.loading = false
          }, 200)
        }).catch(error => {
          console.log(error)
          this.loading = false
        })
      } else { // 获取未绑定的用户
        this.loading = true
        getUsersByRoleIdNotBind(param).then(res => {
          if (res.data && res.data.results) {
            this.userData = res.data.results
            this.page.total = res.data.total
          }
          setTimeout(() => {
            this.loading = false
          }, 200)
        }).catch(error => {
          console.log(error)
          this.loading = false
        })
      }
    },
    getSelectedUserId() {
      const userIds = []
      if (this.selections && this.selections.length > 0) {
        this.selections.forEach(x => {
          userIds.push(x.id)
        })
      }
      return userIds
    },
    // 选择改变
    selectionChangeHandler(val) {
      this.selections = val
    },
    // 授权 或 取消 授权
    doOption() {
      if (this.isBinded) {
        // 已绑定的 取消授权
        this.toRemoveUserIdsByRoleId({ roleId: this.bindRoleId, userIds: [...this.getSelectedUserId()] })
      } else {
        // 已绑定的 添加授权
        this.toAddUserIdsByRoleId({ roleId: this.bindRoleId, userIds: [...this.getSelectedUserId()] })
      }
    },
    // 操作结束
    optEnd() {
      this.bloading = false // 取消 loading
      this.visible = false // 关闭确定弹出
    },
    // 绑定角色到用户
    bindUserId(row) {
      if (this.isBinded) {
        // 已绑定的，移除绑定
        this.toRemoveUserIdsByRoleId({ roleId: this.bindRoleId, userIds: [row.id] })
      } else {
        this.toAddUserIdsByRoleId({ roleId: this.bindRoleId, userIds: [row.id] })
      }
    },
    removeUserId(row) {
      this.toRemoveUserIdsByRoleId({ roleId: this.bindRoleId, userIds: [row.id] })
    },
    // 移除用户授权
    toRemoveUserIdsByRoleId(param) {
      this.bloading = true
      removeUserIdsByRoleId(param).then(res => {
        this.$notify({
          title: '提示',
          message: '取消授权成功',
          type: 'success',
          duration: 2500
        })
        this.optEnd()
        this.getUsersData(this.bindRoleId, this.bindRoleName, this.isBinded)
      }).catch(error => {
        this.optEnd()
        console.log(error)
      })
    },
    // 添加用户数据
    toAddUserIdsByRoleId(param) {
      this.bloading = true
      addUserIdsByRoleId(param).then(res => {
        this.$notify({
          title: '提示',
          message: '授权成功',
          type: 'success',
          duration: 2500
        })
        this.optEnd()
        this.getUsersData(this.bindRoleId, this.bindRoleName, this.isBinded)
      }).catch(error => {
        this.optEnd()
        console.log(error)
      })
    }
  }

}
</script>

<style scoped>

</style>
